<script lang="jsx" setup>
import {
  reactive,
  ref,
  customRef,
  nextTick,
  watch,
  computed,
  onMounted,
  onUnmounted,
  onActivated,
  getCurrentInstance,
  toRef
} from 'vue'
import lodash from 'lodash'
import { ElMessage } from 'element-plus'

const props = defineProps(['scanData'])
const infos = ref({})
const infoKeys = computed(() => Object.keys(infos.value))
const selected = ref()
const headers = ref({})
const displayInfos = computed(() => {
  const infos2 = infos.value[selected.value]
  const searchs2 = searchs.value[selected.value]
  if (infos2 && searchs2) {
    return infos2.filter((item) => {
      for (const key in searchs2) {
        if ((item[key] + '').indexOf(searchs2[key]) === -1) {
          return false
        }
      }
      return true
    })
  }
  return infos2
})
const searchs = ref({})

watch(
  () => props.scanData,
  (newVal) => {
    if (newVal?.scan) {
      for (const key in infos.value) {
        const tabInfos = infos.value[key].filter((item2) => item2['序号'] === focusRow['序号'])
        tabInfos[0]['卷号'] = newVal.scan
      }
    }
  },
  { deep: true }
)

watch(
  () => searchs.value?.[selected.value]?.['序号'],
  (newVal) => {
    for (const key in searchs.value) {
      searchs.value[key]['序号'] = newVal ?? ''
    }
  },
  { deep: true, immediate: true }
)

const writeExcelDebounce = lodash.debounce(() => {
  window.api.writeExcel(JSON.stringify({ title: '自动保存', items: infos.value }))
}, 500)

watch(
  () => infos.value,
  (newVal) => {
    writeExcelDebounce()
  },
  { deep: true }
)

const readExcel = () => {
  window.api.readExcel((data) => {
    infos.value = {}
    for (const key in data) {
      headers.value[key] = data[key][0]
      searchs.value[key] = {}
      const infoList = []
      for (let index = 1; index < data[key].length; index++) {
        const element = data[key][index]
        const row = {}
        element.forEach((element2, index2) => {
          row[headers.value[key][index2]] = element2
        })
        row['备注'] = ''
        row['状态'] = '空'
        row['卷号'] = row['卷号'] ?? ''
        infoList.push(row)
      }
      headers.value[key].push('状态')
      headers.value[key].push('卷号')
      headers.value[key].push('备注')
      infos.value[key] = infoList
    }
    selected.value = infoKeys.value[0]
  })
  return false
}

const copyItem = (item) => {
  const tab1Infos = infos.value[infoKeys.value[0]].filter((item2) => item2['序号'] === item['序号'])
  const tab2Infos = infos.value[infoKeys.value[1]].filter((item2) => item2['序号'] === item['序号'])
  const text = `卡号：${tab1Infos[0]['卡号']}\n卡密：${tab2Infos[0]['卡密']}`
  navigator.clipboard.writeText(text)
  ElMessage({
    message: `${text}\n复制成功`,
    type: 'success'
  })
}

const writeoff = (item) => {
  const tab1Infos = infos.value[infoKeys.value[0]].filter((item2) => item2['序号'] === item['序号'])
  const tab2Infos = infos.value[infoKeys.value[1]].filter((item2) => item2['序号'] === item['序号'])
  if (item['状态'] === '已核销') {
    tab1Infos[0]['状态'] = '空'
    tab2Infos[0]['状态'] = '空'
    ElMessage({
      message: `${item['序号']}，取消成功`,
      type: 'success'
    })
  } else {
    tab1Infos[0]['状态'] = '已核销'
    tab2Infos[0]['状态'] = '已核销'
    ElMessage({
      message: `${item['序号']}，核销成功`,
      type: 'success'
    })
  }
}

const writeExcel = () => {
  if (selected.value && infos.value[selected.value].length) {
    window.api.writeExcel(JSON.stringify({ title: '手动保存', items: infos.value }))
    ElMessage({
      message: `保存成功，保存位置在程序目录的save文件夹下，按日期时间排序`,
      type: 'success'
    })
  } else {
    ElMessage({
      message: `保存失败，还没导入excel`,
      type: 'error'
    })
  }
}

let focusRow = {}

const onFocusJuanhao = (props) => {
  focusRow = props.row
}
</script>

<template>
  <div class="flex flex-col justify-center items-center w-screen h-screen box-border p-3">
    <div class="flex flex-row justify-end items-center h-[40px] w-full pb-2">
      <el-button type="primary" size="default" @click="readExcel">选择excel</el-button>
      <el-button type="primary" size="default" @click="writeExcel">手动保存</el-button>
    </div>
    <div class="flex-1 w-full h-0">
      <template v-if="selected && infos[selected].length">
        <el-tabs v-model="selected" type="card" tab-position="top">
          <el-tab-pane v-for="(item, index) in infoKeys" :key="index" :label="item" :name="item">
          </el-tab-pane>
        </el-tabs>
        <el-table :data="displayInfos" border :style="{ width: '100%', height: 'calc(100% - 60px)' }">
          <template v-for="(item, index) in headers[selected]" :key="index">
            <el-table-column :prop="item" :label="item">
              <template #header="props">
                <div class="text-center">{{ props.column.property }}</div>
                <el-input v-if="props.column.property !== '状态'" v-model="searchs[selected][item]" size="small"
                  placeholder="请输入内容搜索" />
                <el-select v-else v-model="searchs[selected][item]" placeholder="请选择条件" size="small" clearable>
                  <el-option label="空" value="空"> </el-option>
                  <el-option label="已核销" value="已核销"> </el-option>
                </el-select>
              </template>
              <template #default="props">
                <template v-if="['卷号', '备注'].includes(item) && props.row['状态'] !== '已核销'">
                  <el-input v-model="props.row[item]" size="small" placeholder="请输入内容" @focus="onFocusJuanhao(props)" />
                </template>
                <div v-else>{{ props.row[item] }}</div>
              </template>
            </el-table-column>
          </template>
          <el-table-column prop="操作" label="操作">
            <template #header="{ row, column }">
              <div class="text-center">操作</div>
            </template>
            <template #default="{ row, column }">
              <el-button type="primary" size="small" @click="copyItem(row)">复制</el-button>
              <el-button type="primary" size="small" @click="writeoff(row)">{{
                row['状态'] === '已核销' ? '取消' : '核销'
              }}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template v-else>
        <el-empty description="excel还没导入" />
      </template>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>
